from django import forms
from django.contrib.auth import authenticate,login
import re
from index.models import User
from django.contrib.auth.hashers import make_password

# password = 'admin'  # 要加密的字符
# encrypted_password = make_password(password)
# print(encrypted_password)

class LoginForm(forms.Form):
	'''登录表单'''

	username = forms.CharField(label='用户名',
								max_length=100,
								required=False,
								help_text='使用帮助',
								initial='admin')
	password = forms.CharField(label='密码',max_length=200 , min_length=5) 


	def __init__(self,*args,**kwargs):
		super().__init__(*args,**kwargs)
		# 当前登录用户
		self.user = None

	
	def clean_username(self):
		username =self.cleaned_data['username']
		pattern = r'^1[0-9]{10}$'
		if not re.search(pattern,username):
			raise forms.ValidationError('手机号不正确',code='invalid_phone',params=(username,))
		return username


	def clean(self):
		data = super().clean()
		# print(data)
		#如果单个字段错误，直接返回，不执行后面得验证
		if self.errors:
			return 

		username =data.get('username',None)
		password = data.get('password',None)

		# print(username,password)

		print(f"用户名{username}")
		print(f"密码{password}")

		# print("获取到的用户名：", username)
    	# print("获取到的密码：", password)

		user=authenticate(username=username,password=password,model=User)

		print(f"验证之后：{user}")
		
		if user is None:
			raise forms.ValidationError('用户名密码不对')
		else:
			if not user.is_active:
				raise forms.ValidationError('该用户呗禁用')

		self.user = user
		
		return data


	def do_login(self,request):
		""" 执行用户的登陆"""
		user = self.user
		login(request, user)
			
		return user


class UserForm(forms.Form):

	'''用户编辑'''
	SEX_CHOICES = ((1,'女'),(0,'男'))

	email = forms.EmailField(label='邮件',
							max_length=200)

	age = forms.IntegerField(label='年龄')

	sex = forms.ChoiceField(label='性别',choices = SEX_CHOICES)

	bir_day = forms.DateField(label='生日')




class searchForm(forms.Form):
	'''搜索表单'''
	keywords = forms.CharField(label='搜索',max_length=1000,required=True)




class UserRegForm(forms.Form):
	username = forms.EmailField(label='用户名',max_length=200,min_length =5)
	password = forms.CharField(label='密码',max_length = 200,min_length = 5,widget=forms.PasswordInput)
	nickname = forms.CharField(label='昵称',max_length = 32,required=False)
	birth = forms.DateField(label='生日',required=False)
